﻿using Dapper;
using Dm;
using S_Examine.Domains.Entity;
using System.Data;
using System.Data.Common;
using System.Drawing.Printing;
using System.Linq.Expressions;
using static Mysqlx.Expect.Open.Types;

namespace S_Examine.Infrastructure
{
	public class DapperBaseRepository<T> : IDapperRepository<T> where T : class, new()
	{
		public DapperDbContext _db;

		public DapperBaseRepository(DapperDbContext db)
		{
			_db = db;
		}

		public async Task<List<T>> GetAllAsync(string sql)
		{
			IDbConnection dbConnection = _db.Connection;
			{
				try
				{ 
					if (dbConnection.State == ConnectionState.Closed)
					{
						dbConnection.Open();
					}

					return dbConnection.QueryAsync<T>(sql).Result.ToList();
				}
				finally
				{
					if (dbConnection.State == ConnectionState.Open)
					{
						dbConnection.Close();
					}
				}
			}
		}

		public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre, string sql)
		{
			IDbConnection dbConnection = _db.Connection;
			{
				try
				{
					if (dbConnection.State == ConnectionState.Closed)
					{
						dbConnection.Open();
					}

					return dbConnection.QueryAsync<T>(sql, new { expre }).Result.ToList();
				}
				finally
				{
					if (dbConnection.State == ConnectionState.Open)
					{
						dbConnection.Close();
					}
				}
			}
		}

		public async Task<T> GetByFuncAsync(Expression<Func<T, bool>> expre, string sql)
		{
			IDbConnection dbConnection = _db.Connection;
			{
				try
				{
					if (dbConnection.State == ConnectionState.Closed)
					{
						dbConnection.Open();
					}

					return await dbConnection.QueryFirstOrDefaultAsync<T>(sql, new { expre });
				}
				finally
				{
					if (dbConnection.State == ConnectionState.Open)
					{
						dbConnection.Close();
					}
				}
			}
		}

		public async Task<T> GetByIdAsync(int id, string sql)
		{
			IDbConnection dbConnection = _db.Connection;
			{
				try
				{
					if (dbConnection.State == ConnectionState.Closed)
					{
						dbConnection.Open();
					}

					return await dbConnection.QuerySingleAsync<T>(sql, new { Id = id });
				}
				finally
				{
					if (dbConnection.State == ConnectionState.Open)
					{
						dbConnection.Close();
					}
				}
			}
		}
	}
}
